package com.emapp.lccode.activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.emapp.lccode.R
import com.emapp.lccode.adapter.MyViewPgerKtAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.base.appViewModel
import com.emapp.lccode.databinding.ActivityMain2Binding
import com.emapp.lccode.mode.Main2ViewModel
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.PeriodicTask
import com.emapp.lccode.utils.isInternetConnected
import com.emapp.lccode.utils.toStartActivity
import com.google.android.material.navigation.NavigationBarView
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import com.mylhyl.circledialog.CircleDialog
import com.umeng.commonsdk.stateless.UMSLEnvelopeBuild.mContext
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.network.manager.NetState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 项目主页Activity
 */
class MainKtActivity : BaseActivity1<Main2ViewModel, ActivityMain2Binding>(),
    NavigationBarView.OnItemSelectedListener {
    var exitTime = 0L
    private val handler = Handler(Looper.getMainLooper())
    val user = BaseApplication.instance.getUser()
    private val periodicTask = PeriodicTask(60 * 1000L) {
        EventBus.getDefault().post(EventBusModel(EventBusConfig.UP_LAT))
    }

    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            fullScreen(true)
            statusBarDarkFont(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        if (MmkvUtil.getInt("city_version", 6) != BaseConfig.v) {
            toStartActivity(LoginKtActivity::class.java)
            finish()
        }
        EventBus.getDefault().register(this)
        periodicTask.start()
        if (user?.controll_sta == null) {
            if (BaseConfig.v != 3) {//济南市未开放。开放后删掉
                toStartActivity(LoginKtActivity::class.java)
                finish()
            }
        }
        if (user?.isChecker() == true) {
        } else {
            mViewBind.navigation.menu.removeItem(R.id.check)
        }
        mViewBind.viewPager.adapter = MyViewPgerKtAdapter(this)
        if (MmkvUtil.getBoolean("loc_permission", false))
            mViewBind.viewPager.offscreenPageLimit = mViewBind.navigation.menu.size()
        mViewBind.viewPager.isUserInputEnabled = false
        mViewBind.navigation.setOnItemSelectedListener(this)
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    Toaster.show("再按一次返回键退出程序")
                    exitTime = System.currentTimeMillis()
                } else {
                    finish()
                }
            }
        })
        Handler(Looper.getMainLooper()).postDelayed({
            if (!isInternetConnected(appContext)) {
                CircleDialog.Builder()
                    .setTitle("手机无网络")
                    .setCancelable(false)
                    .setSubTitle("请连接互联网后访问App")
                    // .setNegative("取消", null)
                    .setPositive("确定") {
                        //Toaster.show("正在重启")
                        true
                    }
                    .show(supportFragmentManager)
            }
        }, 2000)

    }

    override fun createObserver() {
        mViewModel.run {
            version.observe(this@MainKtActivity) { result ->
                if (result == null)
                    return@observe
                val b = AllenVersionChecker
                    .getInstance()
                    .downloadOnly(
                        UIData.create().setDownloadUrl(result.domain).setTitle("检测到新版本")
                            .setContent("是否更新？")
                    )
                if (result.force_update == "1") {
                    b.setForceUpdateListener {
                        //  Toaster.show("强制更新")
                        handler.run {
                            postDelayed({
                                mViewModel.getVersion2(false)

                            }, 1500)
                        }
                    }
                }

                b.executeMission(this@MainKtActivity)
            }
        }
        handler.run {
            postDelayed({
                mViewModel.getVersion2(false)

            }, 1500)
        }
    }

    /**
     * 示例，在Activity/Fragment中如果想监听网络变化，可重写onNetworkStateChanged该方法
     */
    override fun onNetworkStateChanged(netState: NetState) {
        super.onNetworkStateChanged(netState)
        if (netState.isSuccess) {
            Toast.makeText(applicationContext, "终于有网了啊!", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(applicationContext, "我怎么断网了!", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.home -> {
                mViewBind.viewPager.currentItem = 0
            }

            R.id.check -> {
                mViewBind.viewPager.currentItem = 1
            }

            R.id.me -> {
                mViewBind.viewPager.currentItem = 2
            }
        }
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        periodicTask.stop()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.FINISH -> {

                val it = Intent(this, LoginKtActivity::class.java)
                startActivity(it)
                finish()
            }

            EventBusConfig.FINISH_APP -> {
                finish()
            }

            else -> {}
        }
    }
}
